import React, { useState, useEffect } from 'react';
import { Table, Row, Col, Input } from 'antd';

export default function DeviceData(props) {
  const [data, setData] = useState(props.data || [])
  const [params, setParams] = useState({ name: '' })

  useEffect(() => {
    setData(props.data.filter(item => paramsFilter(item, params)))
  }, [params])

  function paramsFilter(record, params) {
    let result = true
    Object.keys(params).forEach(key => {
      let value = params[key]
      if (value) {
        if (key === 'name') {
          console.log(record.name.indexOf(value) === -1 && record.code.toString().indexOf(value) === -1)
          if (record.name.indexOf(value) === -1 && record.code.toString().indexOf(value) === -1) return result = false
        } else {
          if (record[key].indexOf(value) === -1) return result = false
        }
      }
    })
    return result
  }

  const columns = [
    {
      title: '序号',
      key: 'index',
      render: (text, record, index) => index + 1
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '数值',
      dataIndex: 'value',
      key: 'value',
    },
  ]

  return (
    <>
      <Row type='flex' justify='end' style={{ marginBottom: 10 }}>
        <Col span={8}>
          <Input.Search placeholder='请输入名称' onSearch={(value) => setParams({ ...params, name: value })} />
        </Col>
      </Row>
      <Table columns={columns} dataSource={data} pagination={false} rowKey={(record, index) => index}></Table>
    </>
  )
}
